const httpRequest = require('../util/httpRequest.js');
const { theme, shop } = require('../config');
var { theme_config, storeConfig } = require('../mock/globals');
const { get_nav } = require('../mock/tag');
const { getBlockSections } = require('../util');
const mock = require('../mock');
const { mockProduct, get_collection } = require('../mock/tag');
const { globalCache } = require('@app/util/memoryCache');

// 定义模块对象
const requestAdminService = {
  getBlock: async (route, route_handle) => {
    const TempID = theme.getTemplateId();
    if (TempID) {
      const { data } = await httpRequest.get(
        `/api/themes/${TempID}/data`,
        {
          route: route,
          route_handle: route_handle,
        },
        false
      );
      return data.sections;
    }
    return getBlockSections(route);
  },
  async getThemeConfig(current_route, current_route_handle) {
    const TempID = theme.getTemplateId();
    const themeConfig = theme_config();
    if (TempID) {
      const { data } = await httpRequest.get(`/api/themes/${TempID}/data`, {
        route: current_route,
        route_handle: current_route_handle,
      });
      themeConfig['global'] = data.global;
    }
    return themeConfig;
  },
  async getStoreConfig() {
    if (shop.TOKEN) {
      const { data } = await httpRequest.get('/api/store');
      return data;
    }
    return storeConfig;
  },
  async getNav(id) {
    if (!id) {
      return [];
    }
    if (theme.getTemplateId()) {
      const { data } = await httpRequest.get(`/api/navs/${id}`);

      return data;
    }
    return get_nav;
  },
  async getCurrencies() {
    if (theme.getTemplateId()) {
      const { data } = await httpRequest.get('/api/currencies');
      return data;
    }
    return globalCache.get('global_countrys') || mock.currencies.data;
  },
  async getProduct(id) {
    if (!id) {
      return {};
    }
    if (theme.getTemplateId()) {
      const { data } = await httpRequest.get(`/api/products/${id}`);
      if (data.inventory_tracking && [1, 3].includes(data.inventory_policy)) {
        data.variants.forEach((item) => {
          item['available'] = item['inventory_quantity'] > 0 ? 1 : 0;
          item['image'] = data['images']?.[index];
        });
        data['available'] = data.variants.some((item) => item['available']) ? 1 : 0;
      } else {
        data.variants.forEach((item, index) => {
          item['available'] = 1;
          item['image'] = data['images']?.[index];
        });
        data['available'] = 1;
      }
      return data;
    }
    return mockProduct;
  },
  async getProductList(limit, collection_id) {
    if (!collection_id) {
      return {};
    }
    if (theme.getTemplateId()) {
      const { data } = await httpRequest.get('/api/products/base', {
        pagesize: limit || 10,
        page: 1,
        collection_id: collection_id,
      });
      return data.list;
    }
    const products = [];
    const size = limit || 10;
    for (let i = 0; i < size; i++) {
      products.push(mockProduct);
    }

    return products;
  },
  // 获取专辑信息
  async getCollection(id) {
    if (!id) {
      return {};
    }
    if (theme.getTemplateId()) {
      const { data } = await httpRequest.get(`/api/collections/${id}`);
      return data.collection;
    }
    return get_collection;
  },
  async getThemes() {
    const { data } = await httpRequest.get('/api/themes');
    return data;
  },

  // ============= 缓存相关接口 =============

  /**
   * 设置缓存
   * @param {string} key - 缓存键
   * @param {any} value - 缓存值
   * @param {number} ttl - 过期时间(毫秒)，默认5分钟
   * @returns {boolean} - 是否设置成功
   */
  setCache(key, value, ttl = 300000) {
    try {
      return globalCache.set(key, value, ttl);
    } catch (error) {
      console.error('设置缓存失败:', error);
      return false;
    }
  },

  /**
   * 获取缓存
   * @param {string} key - 缓存键
   * @returns {any} - 缓存值，不存在或过期返回null
   */
  getCache(key) {
    try {
      return globalCache.get(key);
    } catch (error) {
      console.error('获取缓存失败:', error);
      return null;
    }
  },

  /**
   * 删除缓存
   * @param {string} key - 缓存键
   * @returns {boolean} - 是否删除成功
   */
  deleteCache(key) {
    try {
      return globalCache.delete(key);
    } catch (error) {
      console.error('删除缓存失败:', error);
      return false;
    }
  },

  /**
   * 清空所有缓存
   * @returns {boolean} - 是否清空成功
   */
  clearCache() {
    try {
      globalCache.clear();
      return true;
    } catch (error) {
      console.error('清空缓存失败:', error);
      return false;
    }
  },

  /**
   * 检查缓存是否存在
   * @param {string} key - 缓存键
   * @returns {boolean} - 是否存在且未过期
   */
  hasCache(key) {
    try {
      return globalCache.has(key);
    } catch (error) {
      console.error('检查缓存失败:', error);
      return false;
    }
  },

  /**
   * 获取缓存信息
   * @returns {object} - 缓存统计信息
   */
  getCacheInfo() {
    try {
      return {
        size: globalCache.size(),
        keys: globalCache.keys(),
        timestamp: Date.now(),
        data: globalCache.getAllData(),
      };
    } catch (error) {
      console.error('获取缓存信息失败:', error);
      return { size: 0, keys: [], timestamp: Date.now(), data: {} };
    }
  },

  /**
   * 批量设置缓存
   * @param {object} dataMap - 键值对对象
   * @param {number} ttl - 过期时间(毫秒)
   * @returns {boolean} - 是否全部设置成功
   */
  setBatchCache(dataMap, ttl = 300000) {
    try {
      let success = true;
      for (const [key, value] of Object.entries(dataMap)) {
        if (!requestAdminService.setCache(key, value, ttl)) {
          success = false;
        }
      }
      return success;
    } catch (error) {
      console.error('批量设置缓存失败:', error);
      return false;
    }
  },

  /**
   * 存储对象到缓存（主要接口）
   * @param {string} key - 缓存键
   * @param {object} data - 要存储的对象数据
   * @param {number} ttl - 过期时间(毫秒)，默认10分钟
   * @returns {object} - 操作结果
   */
  storeObjectToCache(key, data, ttl = 600000) {
    try {
      if (!key || typeof key !== 'string') {
        return {
          success: false,
          message: '缓存键必须是非空字符串',
          code: 400,
        };
      }

      if (!data || typeof data !== 'object') {
        return {
          success: false,
          message: '数据必须是对象类型',
          code: 400,
        };
      }

      // 深拷贝对象以避免引用问题
      const clonedData = JSON.parse(JSON.stringify(data));

      const result = requestAdminService.setCache(key, clonedData, ttl);

      if (result) {
        return {
          success: true,
          message: '对象存储成功',
          code: 200,
          data: {
            key: key,
            ttl: ttl,
            timestamp: Date.now(),
            size: JSON.stringify(clonedData).length,
          },
        };
      } else {
        return {
          success: false,
          message: '对象存储失败',
          code: 500,
        };
      }
    } catch (error) {
      console.error('存储对象到缓存失败:', error);
      return {
        success: false,
        message: `存储失败: ${error.message}`,
        code: 500,
      };
    }
  },

  /**
   * 从缓存获取对象
   * @param {string} key - 缓存键
   * @returns {object} - 操作结果
   */
  getObjectFromCache(key) {
    try {
      if (!key || typeof key !== 'string') {
        return {
          success: false,
          message: '缓存键必须是非空字符串',
          code: 400,
          data: null,
        };
      }

      const data = requestAdminService.getCache(key);

      if (data !== null) {
        return {
          success: true,
          message: '获取对象成功',
          code: 200,
          data: data,
        };
      } else {
        return {
          success: false,
          message: '缓存中不存在该键或已过期',
          code: 404,
          data: null,
        };
      }
    } catch (error) {
      console.error('从缓存获取对象失败:', error);
      return {
        success: false,
        message: `获取失败: ${error.message}`,
        code: 500,
        data: null,
      };
    }
  },
};

// 导出模块
module.exports = requestAdminService;
